package com.ethink.platform.controller.order;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.ethink.framework.common.web.BaseController;
import com.ethink.framework.common.web.context.SPRequestContextHolder;
import com.ethink.framework.common.web.response.CommonResponse;
import com.ethink.order.api.PurchaseOrderFacade;
import com.ethink.order.api.PurchaseReturnOrderFacade;
import com.ethink.order.api.enums.PurchaseReturnOrderReturnTypeEnum;
import com.ethink.order.api.info.PurchaseReturnDetailOrderInfo;
import com.ethink.order.api.info.PurchaseReturnOrderModeInfo;
import com.ethink.order.api.model.PurchaseReturnDetailModel;
import com.ethink.order.api.model.PurchaseReturnModel;
import com.ethink.order.api.request.PurchaseReturnOrderAddRequest;
import com.ethink.order.api.request.PurchaseReturnOrderUpdateRequest;
import com.ethink.order.api.request.PurchaseReturnPageModeQueryRequest;
import com.ethink.order.api.request.PurchaseReturnPageQueryRequest;
import com.ethink.order.api.response.PurchaseOrderDetailQueryResponse;
import com.ethink.order.api.response.PurchaseReturnDetailResponse;
import com.ethink.order.api.response.PurchaseTransferReturnQueryResponse;
import com.ethink.platform.controller.order.info.ExportInfo;
import com.ethink.platform.manager.ExportManager;
import com.ethink.platform.manager.PurchaseReturnManager;
import com.ethink.warehouse.api.MateInventoryFacade;
import com.ethink.warehouse.api.info.MateInventoryDetailInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author default
 * @version 1.0.0
 * @ClassName PurchaseReturnController.java
 * @Description
 * @createTime 2022年12月07日 14:44:00
 */
@Tag(name = "PurchaseReturnController", description = "采购退单 Controller")
@RestController
@Slf4j
@RequestMapping("platform-server/v1/order-service")
public class PurchaseReturnController extends BaseController {

    @Autowired
    private PurchaseReturnOrderFacade purchaseReturnOrderFacade;

    @Autowired
    private PurchaseOrderFacade purchaseOrderFacade;

    @Autowired
    private PurchaseReturnManager purchaseReturnManager;

    @Autowired
    private MateInventoryFacade mateInventoryFacade;

    @Autowired
    private ExportManager exportManager;

    @Operation(summary = "转采购退查询接口")
    @GetMapping("purchaseReturn/transfer/{id}/{returnType}")
    public CommonResponse<PurchaseTransferReturnQueryResponse> transferPurchaseReturn(@PathVariable("id") Long id
            , @PathVariable Integer returnType) {
        PurchaseTransferReturnQueryResponse response = purchaseReturnManager.purchaseTransferQuery(id, returnType);
        return succeedWith(response);
    }

    @Operation(summary = "新增采购退单")
    @PostMapping("purchaseReturn/add")
    public CommonResponse purchaseReturnAdd(@RequestBody PurchaseReturnOrderAddRequest addRequest) {
        addRequest.setCreateUserCode(SPRequestContextHolder.getCurrentSystemUserLoginName());
        addRequest.setCreateUserName(SPRequestContextHolder.getCurrentSystemUserRealName());
        Long id = purchaseReturnOrderFacade.add(addRequest);
        if (PurchaseReturnOrderReturnTypeEnum.S2.eq(addRequest.getReturnType())) {
            PurchaseReturnDetailResponse returnDetailResponse = purchaseReturnOrderFacade.queryDetail(id);
            purchaseReturnManager.lockMateInventory(returnDetailResponse.getItem());
        }
        return succeed();
    }

    @Operation(summary = "采购退单分页查询")
    @GetMapping("purchaseReturn/pageQuery")
    public CommonResponse<List<PurchaseReturnModel>> purchaseReturnPageQuery(PurchaseReturnPageQueryRequest request) {
        return succeedWithPage(purchaseReturnOrderFacade.pageQuery(request));
    }

    @Operation(summary = "采购退单导出")
    @GetMapping("purchaseReturn/exportQuery")
    public CommonResponse<ExportInfo> purchaseReturnExportExcel(PurchaseReturnPageQueryRequest request) {
        return succeedWith(exportManager.exportPurchaseReturnExcel(request));
    }

    @Operation(summary = "采购退单货品模式分页查询")
    @GetMapping("purchaseReturn/pageQueryMode")
    public CommonResponse<List<PurchaseReturnOrderModeInfo>> purchaseReturnPageModeQuery(PurchaseReturnPageModeQueryRequest request) {
        return succeedWithPage(purchaseReturnOrderFacade.pageModeQuery(request));
    }

    @Operation(summary = "采购退单货品模式导出")
    @GetMapping("purchaseReturn/exportQueryMode")
    public CommonResponse<ExportInfo> purchaseReturnPageModeExportExcel(PurchaseReturnPageModeQueryRequest request) {
        return succeedWith(exportManager.exportPurchaseReturnModeExcel(request));
    }

    @Operation(summary = "采购退单详情查询")
    @GetMapping("purchaseReturn/detail/{id}")
    public CommonResponse<PurchaseReturnDetailResponse> purchaseReturnDetailQuery(@PathVariable("id") Long id) {
        PurchaseReturnDetailResponse returnDetailResponse = purchaseReturnOrderFacade.queryDetail(id);
        List<PurchaseReturnDetailModel> item = returnDetailResponse.getItem();
        List<Long> mateInventoryId = CollUtil.getFieldValues(item, "mateInventoryId", Long.class);
        if (CollUtil.isNotEmpty(mateInventoryId)) {
            List<MateInventoryDetailInfo> mateInventoryDetailInfos = mateInventoryFacade.listMateInventoryByIdList(mateInventoryId);
            Map<Long, MateInventoryDetailInfo> map = mateInventoryDetailInfos.stream()
                    .collect(Collectors.toMap(MateInventoryDetailInfo::getId, Function.identity()));
            for (PurchaseReturnDetailModel purchaseReturnDetailModel : item) {
                if (purchaseReturnDetailModel.getMateInventoryId() != null) {
                    MateInventoryDetailInfo mateInventoryDetailInfo = map.get(purchaseReturnDetailModel.getMateInventoryId());
                    purchaseReturnDetailModel.setPurchaseCode(mateInventoryDetailInfo.getPurchaseCode());
                    purchaseReturnDetailModel.setInventoryType(mateInventoryDetailInfo.getInventoryType());
                    purchaseReturnDetailModel.setSubclassCodeName(mateInventoryDetailInfo.getSubWarehouseName());
                    purchaseReturnDetailModel.setExpireDate(mateInventoryDetailInfo.getExpireDate());
                    purchaseReturnDetailModel.setProductDate(mateInventoryDetailInfo.getProductDate());
                    purchaseReturnDetailModel.setCountryOfOrigin(mateInventoryDetailInfo.getCountryOfOrigin());
                    purchaseReturnDetailModel.setProduceCode(mateInventoryDetailInfo.getProduceCode());
                    purchaseReturnDetailModel.setAvailableQty(mateInventoryDetailInfo.getAvailableQty());
                }
            }

        }
        return succeedWith(returnDetailResponse);
    }

    @Operation(summary = "采购退单删除(草稿状态显示)")
    @DeleteMapping("purchaseReturn/delete/{id}")
    public CommonResponse purchaseReturnDelete(@PathVariable Long id) {
        purchaseReturnOrderFacade.delete(id);
        PurchaseReturnDetailResponse returnDetailResponse = purchaseReturnOrderFacade.queryDetail(id);
        purchaseReturnManager.releaseLockMateInventory(returnDetailResponse.getItem());
        return succeed();
    }


    @Operation(summary = "采购退单编辑(草稿状态显示)")
    @PutMapping("purchaseReturn/update")
    public CommonResponse purchaseReturnUpdate(@Validated @RequestBody PurchaseReturnOrderUpdateRequest updateRequest) {
        purchaseReturnOrderFacade.update(updateRequest);
        if (PurchaseReturnOrderReturnTypeEnum.S2.eq(updateRequest.getReturnStatus())) {
            PurchaseReturnDetailResponse returnDetailResponse = purchaseReturnOrderFacade.queryDetail(updateRequest.getId());
            purchaseReturnManager.lockMateInventory(returnDetailResponse.getItem());
        }
        return succeed();
    }

    @Operation(summary = "采购退审批通过(订单状态 = 2)")
    @PutMapping("purchaseReturn/pass/{id}")
    public CommonResponse purchaseReturnPass(@PathVariable Long id) {
        purchaseReturnOrderFacade.pass(id);
        PurchaseReturnDetailResponse response = purchaseReturnOrderFacade.queryDetail(id);
        if (PurchaseReturnOrderReturnTypeEnum.S2.eq(response.getMain().getReturnType())) {
            List<PurchaseReturnDetailOrderInfo> item = response.getItem().stream().map(
                    a ->
                            BeanUtil.copyProperties(a, PurchaseReturnDetailOrderInfo.class)).collect(Collectors.toList());
            purchaseReturnManager.t12(response.getMain(), item, purchaseOrderFacade.getPurchaseOrderInfo(response.getMain().getPurchaseOrderNo()));
        }
        return succeed();
    }


    @Operation(summary = "采购退审批拒绝(订单状态 = 2)")
    @PutMapping("purchaseReturn/refuse/{id}")
    public CommonResponse purchaseReturnRefuse(@PathVariable Long id) {
        purchaseReturnOrderFacade.refuse(id);
        return succeed();
    }


}